package org.BUPT.application.service;

import org.BUPT.domain.model.message.AnswerLiked;
import org.BUPT.domain.model.message.QuestionAnswered;
import org.BUPT.domain.model.question.AnswerBO;
import org.BUPT.domain.service.impl.AnswerServiceImpl;
import org.BUPT.infrastructure.exception.NullObjectException;
import org.BUPT.infrastructure.exception.PersistException;
import org.BUPT.infrastructure.persistent.po.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

@Service
public class AnswerService {
    @Autowired
    org.BUPT.domain.service.AnswerService answerService;
    @Autowired
    MessageService messageService;
    @Autowired
    QuestionService questionService;



    public AnswerBO getAnswer (int id) throws NullObjectException, PersistException {
        Answer answer = answerService.getAnswer(id);
        if (answer!=null&&answer.getIsDel()!=1){
            return new AnswerBO(answer);
        }
        else{
            throw new NullObjectException("所查询的答案不存在");
        }
    }


    public void createAnswer(int userId, int questionId,String content) throws PersistException, NullObjectException {
        if(answerService.isAnswered(questionId,userId)) return ;
        messageService.addMessage(
                new QuestionAnswered(
                        questionId,
                        userId,
                        questionService.getQuestion(questionId).getUserId()
                )
        );
        new AnswerBO()
                .setContent(content)
                .setUserId(userId)
                .setQuestionId(questionId)
                .setCreateTime(new Date()).save();
    }

    public void modifyAnswer(int id,String content) throws NullObjectException, PersistException {
        getAnswer(id)
                .setContent(content)
                .setEditTime(new Date())
                .save();
    }

    public boolean isLiked(int userId,int answerId) throws NullObjectException, PersistException {
        return getAnswer(answerId).isLiked(userId);
    }
    public void likeAnswer(int userId,int answerId) throws NullObjectException, PersistException {
        AnswerBO answerBO = getAnswer(answerId);
        answerBO.like(userId);
        answerBO.save();
        messageService.addMessage(new AnswerLiked(
                answerBO.getQuestionId(),
                userId,
                answerBO.getUserId()
        ));
    }
    public void dislikeAnswer(int userId,int answerId) throws NullObjectException, PersistException {
        AnswerBO answerBO = getAnswer(answerId);
        answerBO.dislike(userId);
        answerBO.save();
    }
}
